import { Form, Button, Select } from 'antd';
import { axconst } from '@/shared/axconst';
import { AxValidator } from '../AxValidator';

const FormItem = Form.Item;
const { Option } = Select;
const { inlineFormItemLayout, inlineFormItemLayoutAllRowTwo, inlineFormItemLayoutAllRowThree } = axconst;
/**
 * 自定义CheckboxGroup
 * @param label 标签
 * @param field 字段名称
 * @param value 值
 * @param placeholder 占位符
 * @param hidden 是否隐藏
 */
export function AxSelectWithOutForm(props) {
  const {
    formItemLayoutFromProps = null,
    mode,
    wholerow,
    hidden,
    label,
    form,
    field,
    value,
    data,
    placeholder,
    required,
    validator,
    handleFormVisible,
    handleChange: handleChangeFromProps,
    ...rest
  } = props;
  const valueField = 'value';
  const displayField = 'text';
  let formItemLayout = {};
  switch (wholerow) {
    case "two":
      formItemLayout = { ...inlineFormItemLayoutAllRowTwo };
      break;
    case "three":
      formItemLayout = { ...inlineFormItemLayoutAllRowThree };
      break;
    default:
      formItemLayout = formItemLayoutFromProps
        ? formItemLayoutFromProps
        : { ...inlineFormItemLayout };
      break;
  }

  const handleChange = val => {
    if (handleChangeFromProps) handleChangeFromProps(data.filter(i => val.indexOf(i[valueField]) > -1));
  }

  return hidden ? null : (
    <FormItem
      {...formItemLayout}
      label={label}
    >
      {form.getFieldDecorator(field, {
        initialValue: value,
        rules: [
          {
            label: label,
            required: required,
            validator: validator ? validator : AxValidator,
          },
        ],
      })(
        <>
          <Select
            allowClear
            mode='multiple'
            style={{ width: '80%' }}
            placeholder={placeholder ? placeholder : `请选择${label}`}
            value={value}
            onChange={handleChange}
            {...rest}
          >
            {data &&
              data.map((d, idx) => (
                <Option
                  key={idx}
                  value={d[valueField] === true ? true : d[valueField] === false ? false : d[valueField]}
                >
                  {d[displayField]}
                </Option>
              ))}
          </Select>
          <Button
            type='primary'
            style={{ width: '20%' }}
            onClick={() => { if (handleFormVisible) handleFormVisible(true); }}
          >
            选择
          </Button>
        </>
      )}
    </FormItem>
  );
}

